'use strict';
const { Service } = require('egg');

class RoleService extends Service {

  async create(payload) {
    const result = await this.app.mysql.insert('role', { name: payload.name, createdAt: this.app.mysql.literals.now });
    const insertSuccess = result.affectedRows === 1;
    return insertSuccess;
  }

  async destroy(roleId) {
    const result = await this.app.mysql.delete('role', { id: roleId });
    const deleteSuccess = result.affectedRows === 1;
    return deleteSuccess;
  }

  async update(roleId, payload) {
    const row = {
      id: roleId,
      name: payload.name
    };
    const result = await this.app.mysql.update('role', row);
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess;
  }

  async show(roleId) {
    const results = await this.app.mysql.select('role', {
      where: { id: roleId }
    });
    let data = results.map((v, i) => {
      const obj = Object.assign({}, v);
      obj.createdAt = this.ctx.helper.formatTime(v.createdAt)
      return obj;
    });
    if (data.length > 0) {
      return data[0];
    } 
    return null;
  }

  async index(payload) {
    var { currentPage, pageSize } = payload
    currentPage = currentPage || 1;
    pageSize = pageSize || 10;
    let skip = ((Number(currentPage)) - 1) * Number(pageSize || 10)
    const results = await this.app.mysql.select('role', {
      orders: [['createdAt', 'desc'], ['id', 'desc']],
      limit: Number(pageSize),
      offset: Number(skip),
    });

    let data = results.map((v, i) => {
      const obj = Object.assign({}, v);
      obj.createdAt = this.ctx.helper.formatTime(v.createdAt)
      return obj;
    });

    return { count: data.length, list: data, pageSize: Number(pageSize), currentPage: Number(currentPage) }
  }
}

module.exports = RoleService;
